package com.king.first.app.watermark;

import com.king.first.bean.WaterSensor;
import com.king.first.utils.ContentUtils;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

import java.time.Duration;

public class Window_EventTime_Tumbling {

    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> waterSensorStream = env
                .socketTextStream(ContentUtils.HOST, 9999)  // 在socket终端只输入毫秒级别的时间戳
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] datas = value.split(",");
                        return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));

                    }
                });

        // 自定义水印
        WatermarkStrategy<WaterSensor> watermarkStrategy = WatermarkStrategy.<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(
                new SerializableTimestampAssigner<WaterSensor>() {
                    @Override
                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                        return element.getTs() * 1000;
                    }
                }
        );

        WindowedStream<WaterSensor, String, TimeWindow> windowWindowedStream =
                waterSensorStream.assignTimestampsAndWatermarks(watermarkStrategy)
                        .keyBy(value -> value.getId())
                        .window(TumblingEventTimeWindows.of(Time.seconds(4)))
                        .allowedLateness(Time.seconds(2));

        windowWindowedStream.sum("vc").print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }


        new WaterSensor();
    }
}
